package com.jf.cloud.auth.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jf.cloud.auth.config.AppConfig;
import com.jf.cloud.auth.dto.OAuthEntity;
import com.jf.cloud.auth.dto.OAuthUserInfoEntity;
import com.jf.cloud.auth.manager.PasswordManager;
import com.jf.cloud.auth.service.AuthAppService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;

@Service
public class AuthAppServiceImpl implements AuthAppService {
    private static final Logger logger = LoggerFactory.getLogger(AuthAppServiceImpl.class);
    @Autowired
    private AppConfig config;
    @Override
    public OAuthUserInfoEntity getBasicInfo(String code) {
        OAuthUserInfoEntity result = new OAuthUserInfoEntity();
        try {

            //通过code获取UserId和access_token
            String oAuthEntityStr = HttpUtil.get(config.getTokenUrl()+"?client_id="+config.getClientId()+"&client_secret="+config.getClientSecret()+"&grant_type=authorization_code&redirect_uri="+ URLEncoder.encode(config.getRedirectUri(), "utf-8") +"&code="+code);
            logger.info(">>>Code不为null调用获取access_token接口返回信息>>>"+oAuthEntityStr);
            OAuthEntity oAuthEntity = JSON.parseObject(oAuthEntityStr, OAuthEntity.class);

            //通过userId和access_token获取用户详细信息
            String jsonstr = HttpUtil.get(config.getBasicinfoUrl() + oAuthEntity.getUser() + "?access_token=" + oAuthEntity.getAccess_token());
            logger.info("用户的实名信息为>>>"+jsonstr);

            JSONObject json = JSON.parseObject(jsonstr);

            String re = json.getString("data");

            result = JSON.parseObject(re,OAuthUserInfoEntity.class);
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
